import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route,
  Redirect,
  Switch
} from 'react-router-dom';
import { connect } from 'react-redux'
import store from './store';
import setAuthToken from './utils/setAuthToken'
import jwt_decode from 'jwt-decode'
import { setCurrentUser, logoutUser } from './actions/authActions'
import './App.css';
import Navbar from './components/layout/Navbar'
import Footer from './components/layout/Footer'
import router from './router'
// 防止页面刷新数据丢失
if (localStorage.jwtToken) {
  setAuthToken(localStorage.jwtToken)
  // 解析token
  const decoded = jwt_decode(localStorage.jwtToken)
  store.dispatch(setCurrentUser(decoded))
  // 判断token是否过期
  // 获取当前时间
  const currentTime = Date.now() / 1000
  // 当前时间大于过期时间
  if (currentTime > decoded.exp) {
    // 过期
    store.dispatch(logoutUser())
    window.location.href = '/login'
  }

}
export class App extends Component {
  render () {
    let { isAuthenticated } = this.props.auth
    return (
      <div className="App">
        <Router>
          <Navbar />
          <Switch>
            {
              router.map((item, i) => {
                return <Route exact={item.exact} path={item.path} key={i} render={(props) => {
                  //登录情况下
                  if (isAuthenticated) {
                    return <item.componentName {...props} routes={item.children} />
                  }
                  // 非授权页面
                  if (!item.auth) {
                    return <item.componentName {...props} routes={item.children} />
                  }
                  // 未登录并页面授权时跳入登录页面
                  return <Redirect to='/login' />
                }} />
              })
            }
          </Switch>
          <Footer />
        </Router>
      </div >
    );
  }
}
// 获取reduce中在actions定义的initalStaten属性值
const mapStateToProps = (state) => ({
  auth: state.auth,
})
// dispatch 方法
const mapDispatchToProps = (dispatch) => {
  return {

  }
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
